﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using System.IO;

namespace TinyCinema.Data
{
    public class Image : INotifyPropertyChanged
    {
        
        private BitmapImage displayImage;
        public BitmapImage DisplayImage
        {
            get { return displayImage; }
            set
            {
                if (displayImage != value)
                {
                    displayImage = value;
                    OnPropertyChanged("DisplayImage");
                }
            }
        }
        public Image() 
        {
            DisplayImage = new BitmapImage();
        }
        public Image(string Base64String)
        {
            DisplayImage = Base64ToImage(Base64String);
        }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
        public string ToBase64String()
        {
            if (DisplayImage == null) return "";
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(DisplayImage));
                encoder.Save(memoryStream);
                return Convert.ToBase64String(memoryStream.ToArray());
            }
        }
        public BitmapImage Base64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.StreamSource = ms;
            bitmapImage.EndInit();
            return bitmapImage;
        }
    }
}
